﻿
var CurrentRole = {};
var CurrentAccess = [];

Ext.onReady(function () {
    PageSafe();

    var rolestore = new Ext.data.JsonStore({
        url: Ext.getClassUrl('BaseManager.RoleView', 'GetRoles'),
        root: 'ResponseObject',
        fields: ['PID', 'RoleName', 'Creater', 'LastUpdate', 'NTime', 'CreateName.UserName'],
        listeners: {
            beforeload: function (st, op) {
                var re = new JsonRequest();
                re.category = CATEGORY.READONLY;
                st.baseParams = re;
                st.proxy.conn.jsonData = re;
            }
        }
    });
    var rolesm = new Ext.grid.CheckboxSelectionModel({
        singleSelect: true,
        listeners: {
            rowselect: function () {
                var k = rolegrid.getSelectionModel().selections.items;
                if (k.length > 0) {
                    CurrentRole = k[0].json;
                    var re = new JsonRequest();
                    re.params.id = CurrentRole.PID;
                    Ext.Ajax.request({
                        url: Ext.getClassUrl('BaseManager.RoleView', 'GetAccess'),
                        jsonData: re,
                        success: function (re, op) {
                            var obj = Ext.decode(re.responseText);
                            if (obj.ResponseObject != null) {
                                CurrentAccess = [];
                                CurrentAccess = obj.ResponseObject;
                                updateTree(CurrentAccess,MenuTree);
                            }
                        }
                    });
                }
            },
            rowdeselect: function () {
                CurrentRole = {};
            }
        }
    });
    var rolegrid = new Ext.grid.GridPanel({
        bodyStyle: 'padding:2px',
        border: false,
        split: true,
        autoHeight: true,
        sm: rolesm,
        loadMask: true, //加载
        columns: [
       rolesm,
       { id: 'RoleName', header: '角色名', width: 100, dataIndex: 'RoleName', sortable: true }
   ],
        store: rolestore
    });

    var MenuTree = new Ext.tree.TreePanel({
        width: 260,
        style: 'padding-left:20px',
        border: false,
        height: 400,
        split: true,
        rootVisible: true,
        useArrows: false, /*去掉树线*/
        autoScroll: true,
        collapseMode: 'mini',
        root: {},
        listeners: {
            render: function () {
                renderTree(MenuTree); /*渲染菜单树*/
            },
            checkchange: function (node, state) {
                if (CurrentRole.PID == null) { Ext.Msg.alert("信息提示", "请选择一个角色"); return; }
                //定义一个权限对象
                var ob = {
                    RoleID: CurrentRole.PID,
                    MenuID: node.attributes.id
                };
                if (state) {
                    //入栈
                    PushArray(CurrentAccess, ob);
                }
                else {
                    //出栈
                    PopArray(CurrentAccess, ob.MenuID);
                }
            }
        }
    });

    var page = new Ext.Viewport({
        layout: 'border',
        items: [{
            region: 'center',
            tbar: [{ xtype: 'label', text: '权限管理' }, '->', { text: '保存权限', iconCls: 'save-icon', handler: function () {
                if (CurrentAccess.length <= 0) { Ext.Msg.alert("信息提示", "请选择角色所属的菜单"); return; }
                var re = new JsonRequest();
                re.params.info = CurrentAccess;
                Ext.Ajax.request({
                    url: Ext.getClassUrl('BaseManager.RoleView', 'UpdateAccess'),
                    jsonData: re,
                    success: function (re, op) {
                        var obj = Ext.decode(re.responseText);
                        if (!obj.HasError) {
                            Ext.Msg.alert("权限管理提示", "角色名为:[" + CurrentRole.RoleName + "]的权限设置成功", function () { rolestore.load(); renderTree(MenuTree); });
                        }
                        else {
                            Ext.Msg.alert("权限管理提示", "权限设置失败，请联系管理员", function () { rolestore.load(); renderTree(MenuTree); });
                        }
                    }
                });
            }
            }],
            layout: 'border',
            items: [{
                region: 'west',
                title: '角色列表',
                style: 'padding:5px',
                width: 200,
                iconCls: 'role-icon',
                items: rolegrid
            }, {
                region: 'center',
                title: '菜单列表',
                style: 'padding:5px',
                iconCls: 'menu-icon',
                items: MenuTree
            }]
        }],
        listeners: {
            render: function () {
                rolestore.load();
            }
        }
    });
});

//根据权限,替换菜单树选中状态
var updateTree = function (c, tree) {
    for (var i = 0; i < c.length; i++) {
        var node = tree.getNodeById(c[0].MenuID);
        if (node != null) {
            PopArray(c, c[0].MenuID);
            node.getUI().toggleCheck(true);
            node.attributes.checked = true;
        }
    }
}

//初始化树
var renderTree = function (tree) {
    var re = new JsonRequest();
    re.category = CATEGORY.READONLY;
    re.params.param = {};
    Ext.Ajax.request({
        url: Ext.getClassUrl('BaseManager.RoleView', 'GetMenus'),
        jsonData: re,
        success: function (re, op) {
            var obj = Ext.decode(re.responseText).ResponseObject;
            var ns = {}, f = tree;
            ns.ChildMenu = obj;
            var r = new Ext.tree.TreeNode({
                id: '0',
                text: '全部菜单'
            });
            var selectedNode = null, selectedId = f.selectedId;
            function appendChild(node, o) {
                if (node.PID == selectedId) {
                    selectedNode = node;
                }
                if (o.ChildMenu != null && o.ChildMenu.length > 0) {
                    for (var a = 0; a < o.ChildMenu.length; a++) {

                        var n = new Ext.tree.TreeNode({
                            id: o.ChildMenu[a].PID,
                            icon: o.ChildMenu[a].SysImg,
                            text: o.ChildMenu[a].MenuName,
                            parentId: o.ChildMenu[a].ParentID,
                            MenuUrl: o.ChildMenu[a].MenuUrl,
                            MenuFm: o.ChildMenu[a].MenuFm,
                            ImgUrl: o.ChildMenu[a].MenuImg,
                            OrderID: o.ChildMenu[a].OrderID,
                            ClassName: o.ChildMenu[a].ClassName,
                            NameID: o.ChildMenu[a].NameID,
                            checked: false
                        });
                        node.appendChild(n);
                        appendChild(n, o.ChildMenu[a]);

                    }
                }
            }
            appendChild(r, ns);
            f.setRootNode(r);

            tree.registerNode(r); /*注册节点, 不然getNodeById(node.id)找不到这个节点*/
            tree.root.expand(true);
        }
    })
}